/*
文件名称：extension.js
功能描述：基础 - 标准扩展类
作者信息：猪油拌饭 paynewea@163.com  QQ-8033559
*/

//获取日期的显示格式yyyy-MM-dd HH:mm:ss
function dateFormat(date, format) {

    if (!date) return;
    if (!format) format = "yyyy-MM-dd";
    switch(typeof date) {
        case "string":
            date = new Date(date.replace(/-/, "/"));
            break;
        case "number":
            date = new Date(date);
            break;
    }
    if (!date instanceof Date) return;
    var dict = {
        "yyyy": date.getFullYear(),
        "M": date.getMonth() + 1,
        "d": date.getDate(),
        "H": date.getHours(),
        "m": date.getMinutes(),
        "s": date.getSeconds(),
        "MM": ("" + (date.getMonth() + 101)).substr(1),
        "dd": ("" + (date.getDate() + 100)).substr(1),
        "HH": ("" + (date.getHours() + 100)).substr(1),
        "mm": ("" + (date.getMinutes() + 100)).substr(1),
        "ss": ("" + (date.getSeconds() + 100)).substr(1)
    }
    return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {
        return dict[arguments[0]];
    });
};

Date.prototype.format= function(format) {
    return dateFormat(this,format);
};

Date.prototype.addTime = function(y_q_m_w_d_h_mi_s_ms,number) {  
     var d = this;
     var k={'y':'FullYear', 'q':'Month', 'm':'Month', 'w':'Date', 'd':'Date', 'h':'Hours', 'mi':'Minutes', 's':'Seconds', 'ms':'MilliSeconds'}; 
     var n={'q':3, 'w':7}; 
     eval('d.set'+k[y_q_m_w_d_h_mi_s_ms]+'(d.get'+k[y_q_m_w_d_h_mi_s_ms]+'()+'+((n[y_q_m_w_d_h_mi_s_ms]||1)*number)+')'); 
     return d; 

};

Date.prototype.addMilliSeconds = function(ms) {
    return this.addTime('ms',ms);
};

Date.prototype.addSeconds = function(s) {
    return this.addTime('s',s);
};

Date.prototype.addMinutes = function(mi) {
    return this.addTime('mi',mi);
};

Date.prototype.addHours = function(h) {
    return this.addTime('h',h);
};

Date.prototype.addDays = function(d) {
    return this.addTime('d',d);
};

Date.prototype.addWeeks = function(w) {
    return this.addTime('w',w);
};

Date.prototype.addMonths = function(m) {
    return this.addTime('m',m);
};

Date.prototype.addYears = function(y) {
    return this.addTime('y',y);
};

//
String.prototype.endWith=function(s){
  if(s==null||s==""||this.length==0||s.length>this.length)
     return false;
  if(this.substring(this.length-s.length)==s)
     return true;
  else
     return false;
  return true;
 };

 String.prototype.startWith=function(s){
  if(s==null||s==""||this.length==0||s.length>this.length)
   return false;
  if(this.substr(0,s.length)==s)
     return true;
  else
     return false;
  return true;
 };

/*
format有两种调用方式：
    var template1="我是{0}，今年{1}了";
    var template2="我是{name}，今年{age}了";
    var result1=template1.format("loogn",22);
    var result2=template2.format({name:"loogn",age:22});
两个结果都是"我是loogn，今年22了"
*/
String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {    
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
　　　　　　　　　　　　var reg= new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

//对字符串或数字等类型进行左扩展
function padLeft(inText, inLen, inChar){
    inChar = inChar == undefined?' ':''+inChar;
    var str = inText==undefined?'':''+inText;
    if (inText.length >= inLen) return inText;
    for(var i=0;i<inLen;i++) str = inChar + str;
    return str.substr(str.length-inLen);
};

String.prototype.padLeft = function(inLen, inChar){
 return padLeft(this,inLen,inChar);
};

//对字符串或数字等类型进行右扩展
function padRight(inText, inLen, inChar){
    inChar = inChar == undefined?' ':''+inChar;
    var str = inText==undefined?'':''+inText;
    if (inText.length >= inLen) return inText;
    for(var i=0;i<inLen;i++) str = str + inChar;
    return str.substr(str.length-inLen);
};

String.prototype.padRight = function(inLen, inChar){
 return padRight(this,inLen,inChar);
};

//数组中是否包含指定项
Array.prototype.contains = function(item){
    for(i=0;i<this.length;i++){
        if(this[i]==item) return true;
    }
    return false;
};

//对数组去掉重复值
Array.prototype.unique = function() { 
    var data = this || []; 
    var a = {}; //声明一个对象，javascript的对象可以当哈希表用 
    for (var i = 0; i < data.length; i++) {
        a[data] = true; //设置标记，把数组的值当下标，这样就可以去掉重复的值 
    }
    data.length = 0;
    for (var j in a) { //遍历对象，把已标记的还原成数组 
        this[data.length] = j;
    }
    return data;
};

//判断字符串中是否包含某个字符
String.prototype.contains = function(str) {
    return this.indexOf(str) > -1 ? true : false;
}


//去掉字符串的空格
String.prototype.trim = function() { 
    return this.replace(/(^\s*)|(\s*$ )/g, "");
}

String.prototype.lTrim = function() {
    return this.replace(/(^\s*)/g, "");
}
    
String.prototype.rTrim = function() {  
    return this.replace(/(\s*$ )/g, ""); 
}

//验证是否为合法的手机号码
String.prototype.isMobile = function() {
    return /^1[3-8]+\d{9}$/.test(this.trim());
}

//验证是否为合法的电话号码或传真 
String.prototype.isPhone = function() {
    return /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$ /.test(this.trim());
}

//验证是否为合法的Email 
String.prototype.isEmail = function() {
    return /^[a-zA-Z0-9_\-]{1,}@[a-zA-Z0-9_\-]{1,}\.[a-zA-Z0-9_\-.]{1,}$ /.test(this.trim());
}

//验证是否为合法的邮编
String.prototype.isPost = function() {
    return /^\d{6}$ /.test(this.trim());
}

//验证是否为合法的网址 
String.prototype.isUrl = function() {
    var strRegex = "^((https|http|ftp|rtsp|mms)://)"
    + "(([0-9a-z_!~*’().&=+$ %-]+: )?[0-9a-z_!~*’().&=+$ %-]+@)?" //验证ftp的user@
    + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // 验证IP形式的URL
    + "|" // 允许IP和DOMAIN（域名）
    + "([0-9a-z_!~*’()-]+\.)*" // 域名- www.
    + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
    + "[a-z]{2,6})" // 一级域名
    + "(:[0-9]{1,4})?" // 端口
    var re = new RegExp(strRegex);
    return re.test(this.trim());
};

/*提供position:fixed的对象横向滚动方法
  调用方法：
            $("#id").scrollFixed({fixed:'left'});
            $("#id").scrollFixed({fixed:'right'});
*/
(function($){
    $.ScrollFixed = function(el, options){ 
        var base = this; 
        base.$el = $(el); 
        base.el = el; 
        var target = base.$el; 
        var original_left = parseInt(target.css('left')); 
        var original_right = parseInt(target.css('right')); 

        var _fix_position = function(){ 
            if(base.options.fixed == 'right'){ 
                target.css('right', ($(window).scrollLeft() + $(window).width() - $(document).width() + original_right) + 'px'); 
            } else if(base.options.fixed == 'left'){ 
                target.css('left', (original_left - $(window).scrollLeft()) + 'px'); 
            } 
        }; 

        var windowResize = function(){ 
            _fix_position(); 
        }; 

        var windowScroll = function(){ 
            _fix_position(); 
        }; 

        base.init = function(){ 
            base.options = $.extend({}, $.ScrollFixed.defaultOptions, options); 
            $(window).resize(windowResize); 
            $(window).scroll(windowScroll); 
            _fix_position(); 
            //console.log(base.options.fixed); 
        }; 
            base.init();         
    }; 

    $.ScrollFixed.defaultOptions = { 
        fixed:'left' 
    }; 

    $.fn.scrollFixed = function(options){ 
        if (this && this!=undefined) {
            return this.each(function(){ 
               (new $.ScrollFixed(this, options)); 
            });
        } 
    }; 
})(jQuery); 

function correctPNG()
{
    var arVersion = navigator.appVersion.split("MSIE")
    var version = parseFloat(arVersion[1])
    if ((version >= 5.5) && (document.body.filters)) 
    {
       for(var j=0; j<document.images.length; j++)
       {
          var img = document.images[j]
          var imgName = img.src.toUpperCase()
          if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
          {
             var imgID = (img.id) ? "id='" + img.id + "' " : ""
             var imgClass = (img.className) ? "class='" + img.className + "' " : ""
             var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
             var imgStyle = "display:inline-block;" + img.style.cssText 
             if (img.align == "left") imgStyle = "float:left;" + imgStyle
             if (img.align == "right") imgStyle = "float:right;" + imgStyle
             if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
             var strNewHTML = "<span " + imgID + imgClass + imgTitle
             + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
             + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
             + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
             img.outerHTML = strNewHTML
             j = j-1
          }
       }
    }    
}

/*----------------------------------界面控件标准方法----------------------------------*/

$(document).ready(function(){
    $("input:text").each(function(){ $(this).attr("initText",$(this).val()); });
    $("input:text").focus(function(){ if ($(this).val() == $(this).attr("initText") && $(this).attr("initText").length > 0) {$(this).val("");} });
    $("input:text").blur(function(){ if ($(this).val().length == 0 && $(this).attr("initText").length >0) $(this).val($(this).attr("initText")); });
    $("textarea").each(function(){ $(this).attr("initText",$(this).html()); });
    $("textarea").focus(function(){ if ($(this).html() == $(this).attr("initText") && $(this).attr("initText").length > 0) {$(this).html("");} });
    $("textarea").blur(function(){ if ($(this).html().length == 0 && $(this).attr("initText").length >0) $(this).html($(this).attr("initText")); });
    correctPNG();
    //document.body.onselectstart=function(){ return false;}
});

//判断当前URL对应的Path文件是否是输入的网址对应的Path(可接收标准参数)
function MatchPathAndArgs(inPath){
    return MatchCurrentPath(inPath) && MatchCurrentArgs(inPath);
}

//内部函数:匹配输入的path中的path和file是否与当前页面相同
function MatchCurrentPath(inPath) {
    if (inPath.indexOf("?") != -1) inPath = inPath.substr(0, inPath.indexOf("?"));
    inPath = inPath.toLocaleLowerCase();
    var inPage = inPath.substr(inPath.lastIndexOf("/") + 1);
    inPath = inPath.substr(0, inPath.lastIndexOf("/") + 1);
    if (inPage.startWith("default.") || inPage.startWith("index.")) inPage = "";
    
    var curPath = location.pathname.toLocaleLowerCase();
    var curPage = curPath.substr(curPath.lastIndexOf("/") + 1);
    curPath = curPath.substr(0, curPath.lastIndexOf("/") + 1);
    if (curPage.startWith("default.") || curPage.startWith("index.")) curPage = "";
   
    return curPath == inPath && curPage == inPage;     
}

//内部函数:匹配输入的path中的args是否与当前页面相同(以inPath参数为准)
function MatchCurrentArgs(inPath) {
    if (inPath.indexOf("?") == -1) return true;
    
    inPath = inPath.substr(inPath.indexOf("?") + 1).toLocaleLowerCase();
    if (inPath == "") return true;
    
    var args = new Object();
    var curArgs = location.search.toLocaleLowerCase();
    if (curArgs.startWith("?")) {
        curArgs = curArgs.substr(1).split("&");
        for(var i=0;i<curArgs.length;i++) {
            if (curArgs[i] == "") continue;
            if (curArgs[i].indexOf("=") == -1)
                args[curArgs[i]] = "N/A";
            else
                args[curArgs[i].split("=")[0]] = unescape(curArgs[i].split("=")[1]);
        }
    }
    
    inPath = inPath.split("&");
    for(var i=0;i<inPath.length;i++) {
        if (inPath[i] == "") continue;
        var key = "", val = "";
        if (inPath[i].indexOf("=") == -1)
            { key = inPath[i];  val = "N/A"; }
        else
            { key = inPath[i].split("=")[0]; val = inPath[i].split("=")[1]; }
       if (args[key] === undefined || args[key] == null) return false;
       if (args[key] != val) return false;
    }
    return true;
}

function CurrentPage(){
    var path = location.pathname;
    if (path.endWith("/")) path += "default.aspx";
    return path;
}

